<template>
  <div>
    <query-table v-if="loadInfo" ref="project_query_table" :page-size="-1" :columns="columns"
                 :table-max-height="tableMaxHeight"
                 :append-buttons="appendQueryButtons" :query-fields="queryFields"
                 dataRequestMethod="post"
                 base-url="/project_info"
                 v-loading="isLoading" selectable show-index/>

    <el-dialog width="50%" title="导入数据" :visible="importDlgVisible"
               :close-on-click-modal="false" @close="importDlgVisible=false">
      <span slot="footer">
        <el-button v-if="importFileList && importFileList.length > 0"
                   type="primary" size="mini" @click="importData">确认导入</el-button>
      </span>
      <el-row>
        <el-col :span="12">
          <upload-dragger :file-list="importFileList" title="只能上传一个文件" :show-file-list="false" limit="1"/>
        </el-col>
        <el-col :span="12">
          <upload-dragger :file-list="importFileList" title="文件列表" :show-file-list="true" limit="1"/>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog width="90%" :title="(this.checkPermission('batch:update') && this.isInit) ?'编辑任务':'查看任务'"
               v-loading="editCommonDlgLoading" :visible="editCommonDlgVisible"
               :close-on-click-modal="false" @close="editCommonDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" @click="saveBatchCommon"
                   :disabled="!this.checkPermission('batch:update') || !this.isInit">保存</el-button>
        <el-button type="danger" size="mini" @click="editCommonDlgVisible = false">取消</el-button>
      </span>

      <div style="margin-bottom: 10px;">
        <span style="width:7px;background-color:#1E90FF;margin-right:3px;display:inline-block;float:left;height:18px;"/>
        基本信息
      </div>
      <custom-field-form v-loading="editCommonDlgLoading" :fields="batchFields" :data="batchInfo" size="small">
        <el-checkbox label="根据经济极限年判断评价期" v-model="batchInfo.cutoff" style="margin-left: 40px;"></el-checkbox>
      </custom-field-form>
      <div style="margin-bottom: 10px;">
        <span style="width:7px;background-color:#1E90FF;margin-right:3px;display:inline-block;float:left;height:18px;"/>
        价格及商品率
      </div>
      <record-table ref="common_data_table" key="common_data_table" border-color="#ccc" :readonly="!this.isInit"
                    v-loading="editCommonDlgLoading" :data="commonDataList" :columns="commonDataColumns"
                    :max-height="300" show-index/>
    </el-dialog>

    <el-dialog width="90%" style="height: 100%"
               :title="(this.checkPermission('batch:update') &&this.batchInfo.state == 'init')?'编辑项目':'查看项目'"
               v-loading="editProjectDlgLoading" :visible="editProjectDlgVisible"
               :close-on-click-modal="false" @close="editProjectDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" :disabled="!this.checkPermission('batch:update') || !this.isInit"
                   @click="saveProject">保存</el-button>
        <el-button type="danger" size="mini" @click="editProjectDlgVisible = false">取消</el-button>
      </span>
      <el-tabs v-model="editTab" tab-position="left">

        <el-tab-pane label="基本信息" name="project" style="height: calc(75vh - 100px);overflow-y: auto;">
          <custom-field-form v-loading="editProjectDlgLoading" :rules="projectRules"
                             :fields="projectFields" :data="projectInfo" size="small"/>
        </el-tab-pane>
        <el-tab-pane label="生产数据" name="yearRelated">
          <record-table ref="project_data_table" key="project_data_table" border-color="#ccc"
                        :readonly="!this.checkPermission('batch:update') || !this.isInit"
                        v-loading="editProjectDlgLoading" :data="projectYearDataList" :columns="projectYearDataColumns"
                        :max-height="450" show-index/>
        </el-tab-pane>
        <el-tab-pane label="成本数据" name="cost" style="height: calc(75vh - 100px);overflow-y: auto;" lazy>
          <page-part title="成本数据">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectCostFields" :data="projectCostData" size="small"/>
          </page-part>
          <page-part title="税费数据">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectTaxFields" :data="projectCostData" size="small"/>
          </page-part>
          <page-part title="固定参数">
            <custom-field-form v-loading="editProjectDlgLoading"
                               :fields="projectFixFields" :data="projectCostData" size="small"/>
          </page-part>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog width="90%" title="选择模板" v-loading="templateDlgLoading" :visible="templateDlgVisible"
               :close-on-click-modal="false" @close="templateDlgVisible=false">
      <span slot="footer">
        <el-button type="primary" size="mini" @click="commonExport">导出</el-button>
        <el-button type="danger" size="mini" @click="templateDlgVisible = false">取消</el-button>
      </span>
      <el-tabs v-model="editTemplateTab" tab-position="left">

        <el-tab-pane label="系统模板" name="system">
          <record-table ref="system_template_table" key="system_template_table" border-color="#ccc" :readonly="true"
                        v-loading="templateDlgLoading" :data="this.systemTemplateList" :columns="templateColumns"
                        @selection-change="systemSelectionChange"
                        :max-height="450" show-index showCheckbox/>
        </el-tab-pane>
        <el-tab-pane label="自定义模板" name="custom">
          <record-table ref="custom_template_table" key="custom_template_table" border-color="#ccc" :readonly="true"
                        v-loading="templateDlgLoading" :data="this.customTemplateList" :columns="templateColumns"
                        showCheckbox @selection-change="customSelectionChange"
                        :max-height="450" show-index/>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog width="90%" title="系数调整" v-loading="adjustRateDlgLoading" :visible="adjustRateDlgVisible"
               :close-on-click-modal="false" @close="adjustRateDlgVisible = false">
      <div>
        <custom-field-form size="small" :data="adjustRateFieldConditon" :fields="adjustRateFields">
          <el-button size="small" type="success" @click="()=>{
                $refs['project_rate_table'].fillCellDataToBottom();
              }">向下填充
          </el-button>
          <el-button size="small" type="success" @click="()=>{
                $refs['project_rate_table'].fillCellDataToRight();
              }">向右填充
          </el-button>
        </custom-field-form>
      </div>
      <span slot="footer">
        <el-button type="primary" size="mini" @click="saveAdjustRate">保存</el-button>
        <el-button type="primary" size="mini" @click="()=>{
          this.saveAdjustRate('compute');

        }">批量计算</el-button>
        <el-button type="danger" size="mini" @click="adjustRateDlgVisible = false">取消</el-button>
      </span>
      <record-table ref="project_rate_table"
                    key="project_rate_table"
                    border-color="#ccc"
                    :data="adjustRatioDataMap[adjustRateType]"
                    :columns="projectRateColumns"
                    :max-height="450" show-index/>
    </el-dialog>
  </div>
</template>
<script>
import UploadDragger from "../../components/upload-dragger";
import CustomFieldForm from "../../components/custom-field-form";
import DataSelect from "../../components/data-select";
import PagePart from "../../components/page-part";

export default {
  name: "BatchManage",
  components: {PagePart, DataSelect, CustomFieldForm, UploadDragger},
  $$route: {
    meta: {
      title: '任务信息',
    }
  },
  props: {
    //页面高度
    pageHeight: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      isLoading: false,
      adjustRatioDataMap: {},
      adjustRateType: 'output_ratio',
      isInit: true,
      adjustRateFields: [
        {
          id: 'adjustRateType',
          name: '调整系数',
          align: 'left',
          defaultValue: 'output_ratio',
          component: {
            id: 'meta-select', type: 'adjust-ratio-type', change: (val) => {
              this.adjustRateType = val;
            }
          },
          colSpan: 8
        }
      ],
      adjustRateFieldConditon: {},
      editTemplateTab: 'system',
      templateColumns: [
        {id: 'name', name: '项目名称', align: 'left'},
        {id: 'createTime', name: '创建时间', colSpan: 8, disabled: true},
      ],
      columns: [
        {id: 'name', name: '项目名称', align: 'left'},
        {id: 'year', name: '项目年度', width: 80},
        {id: 'buildOffice', name: '建设单位', width: 80, type: 'office', showOverflowTooltip: true},
        {id: 'passed', name: '达标情况', width: 80, type: 'meta', source: 'pass-type', showOverflowTooltip: true},
        {id: 'evaluationMethod', name: '评价方式', width: 80, type: 'meta', source: 'evaluation-method'},
        {id: 'totalInvest', name: '建设投资', unit: "万元", width: 100, showOverflowTooltip: true},
        {id: 'afterTax', name: '税后', width: 120, children: [
            {id: 'irrAfterTax', name: '内部收益率', unit: "%", showOverflowTooltip: true},
            {id: 'pbpAfterTax', name: '投资回报期', unit: "年", showOverflowTooltip: true},
            {id: 'npvAfterTax', name: '财务净现值', unit: "万元", showOverflowTooltip: true},
          ]
        },
        {id: 'balance', name: '基准平衡', width: 120, children: [
            {id: 'balanceConstructionInvest', name: '建设投资', unit: "万元", showOverflowTooltip: true},
            {id: 'balanceSumGasOutput', name: '累产气', unit: "亿方", showOverflowTooltip: true},
          ],isHide:()=>{
            return this.batchInfo.productType == 'oil'
          }
        },
        {id: 'balance', name: '基准平衡', width: 120, children: [
            {id: 'balanceConstructionInvest', name: '建设投资', unit: "万元", showOverflowTooltip: true},
            {id: 'balanceSumOilOutput', name: '累产油', unit: "万吨", showOverflowTooltip: true}
          ],isHide:()=>{
            return this.batchInfo.productType == 'gas'
          }
        },

        {
          id: 'operation', name: '操作', type: 'button', width: 320, children: [
            {
              text: '编辑', type: 'primary', click: (row) => {
                this.editProject(row);
              }, isHide: () => {
                return !this.checkPermission('batch:update') || !this.isInit;
              }
            },
            {
              text: '查看', type: 'primary', click: (row) => {
                this.editProject(row);
              }, isHide: () => {
                return this.checkPermission('batch:update') && this.isInit;
              }
            },
            {
              text: '删除', type: 'danger', click: (row) => {
                this.deleteProject(row);
              }, isHide: () => {
                return !this.checkPermission('batch:update') || !this.isInit;
              }
            },
            {
              text: '评价结果', isHide: (row) => {
                return !row.computeId;
              },
              click: (row) => {
                this.openPage('/evaluation/compute-invoke', row.id, {version: row.computeId})
              }
            },
          ]
        },
      ],

      importDlgVisible: false,
      importFileList: [],

      editCommonDlgLoading: true,
      editCommonDlgVisible: false,
      batchFields: [
        {
          id: 'name',
          name: '任务名称',
          rules: [{required: true, message: "请输入名称", trigger: "blur"}],
          colSpan: 8,
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'paramVersion',
          name: '公共参数',
          rules: [{required: true, message: "请选择公共参数", trigger: "blur"}],
          colSpan: 9,
          isDisabled: () => {
           // return !this.checkPermission('batch:update') || !this.isInit
            return true;
          },
          component: {
            id: 'data-select',
            dataUrl: '/settings/common_param_version/queryPublish'
          },
        },
        {
          id: 'modelId', name: '评价模型', disabled: true, colSpan: 7, isDisabled: () => {
            //return !this.checkPermission('batch:update') || !this.isInit
            return true;
          },
          component: {
            id: 'data-select',
            dataUrl: '/settings/model/publish/data'
          },
        },
        {
          id: 'costEvaMethod',
          name: '成本测算方式',
          rules: [{required: true, message: "请选择成本测算方式", trigger: "blur"}],
          colSpan: 8,
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          },
          component: {id: 'meta-select', type: 'cost-eva-method'},
        },
        {
          id: 'createUser', name: '创建人', colSpan: 4, component: {
            id: 'data-select',
            disabled: true,
            getDataUrl: (item)=>{return '/user/name_data?pageSize=-1&id='+item.createUser}
          }
        },
        {id: 'createTime', name: '创建时间', colSpan: 5, disabled: true},
      ],
      batchInfo: {cutoff: true},
      loadInfo:false,
      commonUnitCostMap: {},
      commonDataColumns: [
        {id: 'type', name: '参数名称', width: 150, readonly: true},
        {id: 'year1', name: '第1年'},
        {id: 'year2', name: '第2年'},
        {id: 'year3', name: '第3年'},
        {id: 'year4', name: '第4年'},
        {id: 'year5', name: '第5年'},
        {id: 'year6', name: '第6年'},
        {id: 'year7', name: '第7年'},
        {id: 'year8', name: '第8年'},
        {id: 'year9', name: '第9年'},
        {id: 'year10', name: '第10年'},
        {id: 'year11', name: '第11年'},
        {id: 'year12', name: '第12年'},
        {id: 'year13', name: '第13年'},
        {id: 'year14', name: '第14年'},
        {id: 'year15', name: '第15年'},
        {id: 'year16', name: '第16年'},
        {id: 'year17', name: '第17年'},
        {id: 'year18', name: '第18年'},
        {id: 'year19', name: '第19年'},
        {id: 'year20', name: '第20年'}
      ],
      commonDataList: [
        {code: "oilPrice", type: "原油价格（元/吨）"},
        {code: "gasPrice", type: "天然气价格（元/千方）"},
        {code: "condensatePrice", type: "轻烃价格（元/吨）"},
        {code: "liquidGasPrice", type: "液化气价格（元/吨）"},
        {code: "oilCommodityRate", type: "原油商品率（%）"},
        {code: "gasCommodityRate", type: "天然气商品率（%）"},
        {code: "otherCommodityRate", type: "其他产品商品率（%）"},
      ],

      editProjectDlgLoading: false,
      editProjectDlgVisible: false,
      templateDlgLoading: false,
      templateDlgVisible: false,
      systemTemplateList: [],
      customTemplateList: [],
      multipleCustomSelection: [],
      multipleSystemSelection: [],
      editTab: "project",
      projectRules: {
        evaluationPeriod: [{validator: this.validatorIntegerNum, trigger: "blur"}],
        buildYearCount: [{validator: this.validatorIntegerNum, trigger: "blur"}],
        newAnnualCapacity: [{validator: this.validatorGatherZeroNum, trigger: "blur"}],
        newWellCount: [{validator: this.validatorIntegerNum, trigger: "blur"}],
        outputWellOpenCount: [{validator: this.validatorIntegerNum, trigger: "blur"}],
        injectWellOpenCount: [{validator: this.validatorIntegerNum, trigger: "blur"}],
        drillExtractInvest: [{validator: this.validatorGatherZeroNum, trigger: "blur"}],
        groundInvest: [{validator: this.validatorGatherZeroNum, trigger: "blur"}],
        otherInvest: [{validator: this.validatorGatherZeroNum, trigger: "blur"}],
        netAssetsUnUse: [{validator: this.validatorGatherZeroNum, trigger: "blur"}],
      },
      projectFields: [
        {
          id: 'name',
          name: '项目名称',
          rules: [{required: true, message: "请输入项目名称", trigger: "blur"}],
          colSpan: 16,
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'year', name: '项目年度', colSpan: 8, component: {id: 'year-picker'}, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'buildOffice', name: '建设单位', colSpan: 8,
          component: {
            id: 'data-select', dataUrl: '/company/children_company_set?companyId=21810',load:(dataList,val)=>{
              for (let i = dataList.length -1; i >=0; i--) {
                if (dataList[i].type != "sub_office" && dataList[i].type != 'branch_office') {
                  dataList.splice(i,1);
                }
              }
              dataList.sort((a, b) => {
                if(isNaN(a.sort)||isNaN(b.sort)) {
                  return 0;
                }
                return a.sort - b.sort;
              })
            },
            change:(val)=>{
              this.updateProjectCostData(val)
            }
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'evaluationPeriod', name: '评价期', colSpan: 8, unit: "年", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'buildYearCount', name: '建设年限', colSpan: 8, unit: "年", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'productProperty',
          name: '原油品质',
          colSpan: 8,
          component: {id: 'meta-select', type: 'oil-product-property'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'productProperty',
          name: '天然气品质',
          colSpan: 8,
          component: {id: 'meta-select', type: 'gas-product-property'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'areaMark',
          name: '新老区',
          colSpan: 8,
          component: {id: 'meta-select', type: 'area-mark'},
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'region', name: '大区', colSpan: 8, component: {id: 'meta-select', type: 'oil-region'}, isHide: () => {
            return this.batchInfo.productType == 'gas'
          }, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'region', name: '大区', colSpan: 8, component: {id: 'meta-select', type: 'gas-region'}, isHide: () => {
            return this.batchInfo.productType == 'oil'
          }, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 8,
          component: {id: 'meta-select', type: 'oil-capacity-type'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 8,
          component: {id: 'meta-select', type: 'gas-capacity-type'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 8,
          component: {id: 'meta-select', type: 'oil-displacement-method'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 8,
          component: {id: 'meta-select', type: 'gas-displacement-method'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 8,
          component: {id: 'meta-select', type: 'oil-pool-type-new'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 8,
          component: {id: 'meta-select', type: 'gas-pool-type'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          },
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'other1', name: '其他类型1', colSpan: 8, component: {id: 'meta-select', type: 'other1'}, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'other2', name: '其他类型2', colSpan: 8, component: {id: 'meta-select', type: 'other2'}, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'evaluationMethod',
          name: '评价阶段',
          colSpan: 8,
          component: {id: 'meta-select', type: 'evaluation-method', load: this.methodBeforeDisplayList},
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {id:'productType',name:'产品类型',isHide:()=>{return true}},
        {
          id: 'oilGasField', name: '油气田',
          component: {
            id: 'data-select',
            getDataUrl: () => {
              return '/cascade/queryChildrenList?type=oil-field&parentSource=${productType}';
            },
            valueKey: 'source',
            // load:(dataList,fieldData,field) => {
            //   if(dataList&&dataList.length == 1) {
            //     fieldData.oilGasField = dataList[0].source;
            //   }
            // }
          }, colSpan: 8,
          isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'drillOilWellCount', name: '钻井油井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'drillWaterWellCount', name: '钻井水井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'drillWellCount', name: '钻井井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'straightWellDeth', name: '直井井深', colSpan: 8, unit: "m", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'horizontalWellDeth', name: '水平井深', colSpan: 8, unit: "m", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'intoRuler', name: '进尺', colSpan: 8, unit: "10⁴m", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'infOilWellCount', name: '基建油井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'infWaterWellCount', name: '基建水井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'infWellCount', name: '基建井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'builtUpCapacity', name: '建成能力', colSpan: 8, unit: "10⁴m", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'wellOutput', name: '单井日产', colSpan: 8, unit: "t", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'straightWellOutput', name: '直井单井日产', colSpan: 8, unit: "t", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'horizontalWellOutput', name: '水平单井日产', colSpan: 8, unit: "t", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'horizontalWellCount', name: '钻水平井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'buildHorizontalWellCount', name: '建水平井数', colSpan: 8, unit: "口", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'regionOilGasRate', name: '区块汽油比', colSpan: 8, unit: "m³/t", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'oldNetWorth', name: '待利用井净值', colSpan: 8, unit: "万元", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'baseIrr', name: '基准收益率', colSpan: 8, unit: "%", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'resourceRate', name: '资源税', colSpan: 8, unit: "%", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'productionDay', name: '首年生产天数', colSpan: 8, unit: "天", isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'createUser', name: '创建人', colSpan: 8, component: {
            id: 'data-select',
            disabled: true,
            requestMethod:'post',
            dataUrl: '/user/name_data?pageSize=-1'
          }
        },
        {id: 'createTime', name: '创建时间', colSpan: 8, disabled: true},
      ],
      projectTaxFields: [
        {
          id: 'oilValueAddedTaxRate', name: '原油增值税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasValueAddedTaxRate', name: '天然气增值税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherValueAddedTaxRate', name: '其他产品增值税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'cityConstructionTaxRate', name: '城市维护建设税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'educationSurchargeRate', name: '教育费附加税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        // {
        //   id: 'resourceTaxRate', name: '资源税率', unit: '%', colSpan: 12, isDisabled: () => {
        //     return !this.checkPermission('batch:update') || !this.isInit
        //   }
        // },
        {
          id: 'incomeTaxRate', name: '所得税率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
      ],
      projectFixFields: [
        {
          id: 'potionAmortisePeriod', name: '三元药剂摊销年限', unit: '年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'iaAmortisePeriod', name: '无形资产摊销年限', unit: '年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherAssetsAmortisePeriod', name: '其他资产折旧年限', unit: '年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'loanRepaymentPeriod', name: '借款偿还期', unit: '年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'fixedAssetBorrowRatio', name: '固定资产借款比例', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'disposalFeeRatio', name: '弃置费提取比例', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'longTermLoanInterestRate', name: '长期贷款利率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'liquidBorrowInterestRate', name: '流动资金借款利率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'liquidBorrowInterestRatio', name: '流动资金借款比例', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'liquidOfBusinessRatio', name: '流动资金占经营成本比例', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'costInputTaxOfOptRatio', name: '成本进项税占操作成本比例', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'unitSellCost', name: '单位销售及管理费用', unit: '元/吨', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'surplusReserveRatio', name: '法定盈余公积金', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'exchangeRate', name: '汇率', unit: '人民币/美元', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'tonToBarrelRatio', name: '吨桶比', unit: '桶/t', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'oilGasEquivalent', name: '油气当量', unit: '方/吨', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'condensateEquivalent', name: '凝析油当量', unit: '吨凝析油/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostConventional', name: '其他管理费（常规）', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostDeApportion', name: '其他管理费（扣分摊）', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherManageCostGround', name: '其他管理费（地面评价）', unit: '万元/人·年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostConventional', name: '天然气其他管理费（常规）', unit: '元/万方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostDeApportion', name: '天然气其他管理费（扣分摊）', unit: '元/万方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasManageCostGround', name: '天然气其他管理费（地面评价）', unit: '万元/人·年', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'mineralResourcesComprate', name: '矿业权出让收益率', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'businessCostRatio', name: '营业费用', unit: '%', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'safetyCostRatioOil', name: '安全生产费用（油）', unit: '元/吨', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'safetyCostRatioGas', name: '安全生产费用（气）', unit: '元/千方', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },

      ],
      projectCostFields: [
        {
          id: 'operateCostStandard', name: '单井定额', unit: '万元/油井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'oilQuotaStandard', name: '吨油定额', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'fixedCost', name: '固定成本', unit: '万元/油气井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'variableCost', name: '可变成本', unit: '元/吨油（元/万方）', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'miningOperationPrice', name: '采出作业费', unit: '万元/油井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'waterInjectionPrice', name: '驱油物注入费', unit: '元/方水', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'heavyOilThRecPrice', name: '稠油热采费', unit: '元/吨蒸汽', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'oilGasProcessPrice', name: '油气处理费', unit: '元/吨液', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'condensateRecyclePrice', name: '轻烃回收费', unit: '元/吨油', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'underWellOperationPrice', name: '井下作业费', unit: '万元/油井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'wellTestPrice', name: '测井试井费', unit: '万元/油井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'gasPurificationPrice', name: '天然气净化费', unit: '元/千立方米', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'repairPrice', name: '维护及修理费', unit: '万元/油井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'transferPrice', name: '运输费', unit: '万元/总井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'otherAuxiliaryPrice', name: '其他辅助作业费', unit: '万元/总井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },
        {
          id: 'factoryMineManagePrice', name: '厂矿管理费', unit: '万元/总井数', colSpan: 12, isDisabled: () => {
            return !this.checkPermission('batch:update') || !this.isInit
          }
        },

      ],
      oldBuildOffice:{},
      oldProjectCostData:{},
      projectInfo: {},
      projectCostData: {},
      projectYearDataColumns: [
        {id: 'type', name: '参数名称', width: 150, readonly: true},
        {id: 'sum', name: '合计', width: 65},
        {id: 'year1', name: '第1年', width: 65},
        {id: 'year2', name: '第2年', width: 65},
        {id: 'year3', name: '第3年', width: 65},
        {id: 'year4', name: '第4年', width: 65},
        {id: 'year5', name: '第5年', width: 65},
        {id: 'year6', name: '第6年', width: 65},
        {id: 'year7', name: '第7年', width: 65},
        {id: 'year8', name: '第8年', width: 65},
        {id: 'year9', name: '第9年', width: 65},
        {id: 'year10', name: '第10年', width: 65},
        {id: 'year11', name: '第11年', width: 65},
        {id: 'year12', name: '第12年', width: 65},
        {id: 'year13', name: '第13年', width: 65},
        {id: 'year14', name: '第14年', width: 65},
        {id: 'year15', name: '第15年', width: 65},
        {id: 'year16', name: '第16年', width: 65},
        {id: 'year17', name: '第17年', width: 65},
        {id: 'year18', name: '第18年', width: 65},
        {id: 'year19', name: '第19年', width: 65},
        {id: 'year20', name: '第20年', width: 65},
        {id: 'year21', name: '第21年', width: 65},
        {id: 'year22', name: '第22年', width: 65},
        {id: 'year23', name: '第23年', width: 65},
        {id: 'year24', name: '第24年', width: 65},
        {id: 'year25', name: '第25年', width: 65},
        {id: 'year26', name: '第26年', width: 65},
        {id: 'year27', name: '第27年', width: 65},
        {id: 'year28', name: '第28年', width: 65},
        {id: 'year29', name: '第29年', width: 65},
        {id: 'year30', name: '第30年', width: 65},
      ],
      projectYearDataList: [
        // {code:"sumInvest", type:"合计投资（万元）"},
        {code: "drillExtractInvest", type: "钻采投资（万元）"},
        {code: "groundInvest", type: "地面投资（万元）"},
        {code: "otherInvest", type: "其他投资（万元）"},
        //{code:"productionRate",   type:"生产时率（%）"},
        {code: "outputWellOpenCount", type: "采出井开井数（口）"},
        {code: "injectionWellOpenCount", type: "注入井开井数（口）"},
        {code: "fixedPerson", type: "定员数（人）"},
        {code: "liquidOutput", type: "产液量（万吨）"},
        {code: "oilOutput", type: "原油产量（万吨）"},
        {code: "gasOutput", type: "天然气产量（亿方）"},
        {code: "gasOutput1", type: "天然气产量（万方）"},
        {code: "waterInjection", type: "注水量（万方）"},
        {code: "steamInjection", type: "注蒸汽量（万吨）"},
        {code: "drugCost", type: "药剂费（万元）"},
        {code: "condensateOutput", type: "轻烃产量（万吨）"},
        {code: "liquidGasOutput", type: "液化气产量（万吨）"},
      ],

      adjustRateDlgLoading: false,
      adjustRateDlgVisible: false,
      projectRateColumns: [
        {id: 'year', name: '项目年度', width: 100, fixed: true, readonly: true},
        {id: 'name', name: '项目名称', width: 120, fixed: true, showOverflowTooltip: true, readonly: true},
        {
          id: 'buildOffice',
          name: '建设单位',
          type: "office",
          fixed: true,
          showOverflowTooltip: true,
          width: 120,
          readonly: true
        },
        {id: 'evaluationPeriod', name: '评价期', width: 80, fixed: true, readonly: true},
        {id: 'year1', name: '第1年', width: 65},
        {id: 'year2', name: '第2年', width: 65},
        {id: 'year3', name: '第3年', width: 65},
        {id: 'year4', name: '第4年', width: 65},
        {id: 'year5', name: '第5年', width: 65},
        {id: 'year6', name: '第6年', width: 65},
        {id: 'year7', name: '第7年', width: 65},
        {id: 'year8', name: '第8年', width: 65},
        {id: 'year9', name: '第9年', width: 65},
        {id: 'year10', name: '第10年', width: 65},
        {id: 'year11', name: '第11年', width: 65},
        {id: 'year12', name: '第12年', width: 65},
        {id: 'year13', name: '第13年', width: 65},
        {id: 'year14', name: '第14年', width: 65},
        {id: 'year15', name: '第15年', width: 65},
        {id: 'year16', name: '第16年', width: 65},
        {id: 'year17', name: '第17年', width: 65},
        {id: 'year18', name: '第18年', width: 65},
        {id: 'year19', name: '第19年', width: 65},
        {id: 'year20', name: '第20年', width: 65}
      ],
      projectRateDataList: [],

    }
  },
  computed: {
    //表格最大高度，自适应
    tableMaxHeight() {
      return this.pageHeight - 150;
    },

    appendQueryButtons() {
      return [
        {
          text: '编辑任务', type: 'success', click: this.editBatchCommonData, isHide: () => {
            return !this.checkPermission('batch:update') || !this.isInit;
          }
        },
        {
          text: '查看任务', type: 'success', click: this.editBatchCommonData, isHide: () => {
            return this.checkPermission('batch:update') || this.isInit;
          }
        },
        {
          text: '系数调整', type: 'success', click: this.initAdjustRate, listen: this.batchInfo.state, isHide: () => {
            return !this.checkPermission('batch:update') || !this.isInit;
          }
        },
        {
          text: '版本锁定', type: 'success', click: () => {
            this.openPage('/batch/lock', this.$route.query.id)
          }, isHide: () => {
            return !this.checkPermission('batch:update') || !this.isInit;
          }
        },
        {
          text: '批量计算', type: 'success', click: this.batchCompute, isHide: () => {
            return !this.checkPermission('batch:update') || !this.isInit;
          }
        },
        {
          text: '导入', type: 'warning', click: () => {
            this.importDlgVisible = true
          }, isHide: () => {
            return !this.checkPermission('batch:update') || !this.isInit;
          }
        },
        {
          text: '导出', type: 'warning', click: () => {
            this.loadTemplate("export")
            this.templateDlgVisible = true
          },
          tooltip: {content: '按照一个项目一行的方式将筛选后的项目批量导出到一个Excel工作表中。'}
        },
        {
          text: '批量导出', type: 'warning', click: () => {
            this.loadTemplate("batch_export")
            this.templateDlgVisible = true
          },
          tooltip: {content: '按照一个项目一个sheet的方式，将筛选后的项目批量导出到一个Excel工作簿中。'}
        },
        {
          text: '合并导出', type: 'warning', click: () => {
            this.loadTemplate("merge_export")
            this.templateDlgVisible = true
          },
          tooltip: {content: '将任务中的所有项目按照模板规定的分类，汇总并导出到一个Excel工作表中。'}
        },
      ];
    },
    queryFields() {
      let batchName = '';
      if (this.batchInfo) {
        batchName = this.batchInfo.name;
      }
      return [
        {id: 'batchId', name: '任务id', hide: true, defaultValue: this.$route.query.id},
        {id: 'batchNamed', name: '任务名称', colSpan: 7, disabled: true, defaultValue: batchName},

        {id: 'name', name: '项目名称', colSpan: 7},

        {id: 'year', name: '项目年度', component: 'year-picker', colSpan: 5},
        {id: 'areaMark', name: '新老区', colSpan: 5, component: {id: 'meta-select', type: 'area-mark'}},
        {
          id: 'region',
          name: '大区',
          colSpan: 4,
          listen: this.batchInfo,
          component: {id: 'meta-select', type: 'oil-region'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          }
        },
        {
          id: 'region', name: '大区', colSpan: 4, component: {id: 'meta-select', type: 'gas-region'}, isHide: () => {
            return this.batchInfo.productType == 'oil'
          }
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 5,
          component: {id: 'meta-select', type: 'oil-capacity-type'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          }
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 5,
          component: {id: 'meta-select', type: 'gas-capacity-type'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          }
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 5,
          component: {id: 'meta-select', type: 'oil-displacement-method'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          }
        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 5,
          component: {id: 'meta-select', type: 'gas-displacement-method'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          }
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 5,
          component: {id: 'meta-select', type: 'oil-pool-type-new'},
          isHide: () => {
            return this.batchInfo.productType == 'gas'
          }
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 5,
          component: {id: 'meta-select', type: 'gas-pool-type'},
          isHide: () => {
            return this.batchInfo.productType == 'oil'
          }
        },
        {id: 'buildOffice', name: '建设单位', component: {
            id: 'data-select', dataUrl: '/company/children_company_set?companyId=21810',load:(dataList,val)=>{
              for (let i = dataList.length -1; i >=0; i--) {
                if (dataList[i].type != "sub_office" && dataList[i].type != 'branch_office') {
                  dataList.splice(i,1);
                }
              }
              dataList.sort((a, b) => {
                if(isNaN(a.sort)||isNaN(b.sort)) {
                  return 0;
                }
                return a.sort - b.sort;
              })
            }
          }, colSpan: 5},
        {id: 'passed', name: '达标情况', component: {id: 'meta-select', type: 'pass-type', hideRoot: true}, colSpan: 4},
        {id: 'irrAfterTax', name: '税后内部收益率(%)', component: 'input-number-range', colSpan: 5, unit: ''},
        //{id: 'totalInvest', name: '建设投资', component: 'input-number-range', colSpan: 5},
      ];
    }

  },
  created() {
    this.loadBatchInfo()

  },
  methods: {
    systemSelectionChange(val) {
      this.multipleSystemSelection = val
    },
    customSelectionChange(val) {
      this.multipleCustomSelection = val
    },
    loadTemplate(exportTemplateType) {
      this.loadSystemTemplate(exportTemplateType);
      this.loadCustomTemplate(exportTemplateType);
    },
    loadSystemTemplate(exportTemplateType) {
      this.$get("/template/data", {
        type: 'system',
        tag: this.batchInfo.productType,
        publish: true,
        exportTemplateType: exportTemplateType
      }, (res) => {
        this.systemTemplateList = res.data;
      })
    },
    loadCustomTemplate(exportTemplateType) {
      this.$get("/template/data", {
        type: 'custom',
        tag: this.batchInfo.productType,
        publish: true,
        exportTemplateType: exportTemplateType
      }, (res) => {
        this.customTemplateList = res.data;
      })
    },
    methodBeforeDisplayList(dataList) {
      let list = []
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].id != 'optimize_invest') {
          list.push(dataList[i])
        }
      }
      return list
    },
    // updateRowsStyle({row, rowIndex}){
    //   if (row.ultimate && row.ultimate == true) {
    //     return {background: '#f0f9eb'}
    //   }
    // },
    loadCommonUnitCost: async function(){
      let response = await this.$getHttpPromise("/settings/common_unit_cost/data", {
        versionId: this.batchInfo.paramVersion,
        pageSize: -1
      });
      let dataMap = {};
      if (response.data && response.data.length > 0) {

        for (let item of response.data) {
          dataMap[item.companyId] = item;
        }
        this.commonUnitCostMap = dataMap;
      }
    },
    updateProjectCostData(buildOffice) {
      if (buildOffice == this.oldBuildOffice) {
        this.projectCostData = this.oldProjectCostData
      } else {
        let commonUnitCost = this.commonUnitCostMap[buildOffice]
        this.projectCostData.operateCostStandard = commonUnitCost.operateCostStandard;
        this.projectCostData.miningOperationPrice = commonUnitCost.miningOperationPrice;
        this.projectCostData.waterInjectionPrice = commonUnitCost.waterInjectionPrice;
        this.projectCostData.heavyOilThRecPrice = commonUnitCost.heavyOilThRecPrice;
        this.projectCostData.oilGasProcessPrice = commonUnitCost.oilGasProcessPrice;
        this.projectCostData.condensateRecyclePrice = commonUnitCost.condensateRecyclePrice;
        this.projectCostData.underWellOperationPrice = commonUnitCost.underWellOperationPrice;
        this.projectCostData.wellTestPrice = commonUnitCost.wellTestPrice;
        this.projectCostData.gasPurificationPrice = commonUnitCost.gasPurificationPrice;
        this.projectCostData.repairPrice = commonUnitCost.repairPrice;
        this.projectCostData.transferPrice = commonUnitCost.transferPrice;
        this.projectCostData.otherAuxiliaryPrice = commonUnitCost.otherAuxiliaryPrice;
        this.projectCostData.factoryMineManagePrice = commonUnitCost.factoryMineManagePrice;
        this.projectCostData.oilQuotaStandard = commonUnitCost.oilQuotaStandard;
        this.projectCostData.fixedCost = commonUnitCost.fixedCost;
        this.projectCostData.variableCost = commonUnitCost.variableCost;
      }

    },
    loadBatchInfo: function () {
      this.editCommonDlgLoading = true;
      this.$get("/batch_info/info/" + this.$route.query.id, {}, (response) => {
        this.batchInfo = response.data;
        let table = this.$refs['project_query_table']
        this.isInit = this.batchInfo.state == 'init'
        this.loadInfo = true
        this.loadCommonUnitCost();
        // table.updateQueryCondition('batchNamed',response.data.name);
        // table.updateQueryCondition('batchType',response.data.type);
        // table.updateQueryCondition('productType',response.data.productType);
        //this.loadTemplate();
      }, () => {
        this.editCommonDlgLoading = false;
      });
      this.editCommonDlgLoading = false;
    },
    editBatchCommonData: function () {
      let commonDataDTO = {};
      commonDataDTO.pageSize = -1;
      commonDataDTO.pageNo = 1;
      commonDataDTO.batchId = this.$route.query.id;
      this.editCommonDlgVisible = true;
      this.editCommonDlgLoading = true;
      this.$get("/batch_common_data/data", commonDataDTO, (response) => {
        this.getBatchCommonDataForShow(response.data);
      }, () => {
        this.editCommonDlgLoading = false;
      });
    },
    getBatchCommonDataForShow(oriDataList) {
      let yearPreFix = "year";
      let commonTableDataList = JSON.parse(JSON.stringify(this.commonDataList));
      for (const tableRow of commonTableDataList) {
        for (let i = 1; i < 21; i++) {
          let yearDatas = oriDataList.filter(item => {
            return item[yearPreFix] == i
          });
          if (!yearDatas || yearDatas.length == 0) {
            continue;
          }
          tableRow[yearPreFix + i] = yearDatas[0][tableRow.code];
        }
      }
      this.commonDataList = commonTableDataList;
    },
    importData() {
      let openLoading = this.openLoading("数据导入中···");
      this.$post("/batch_info/importExcel/" + this.importFileList[0].id + "/" + this.batchInfo.id,
          {}, (response) => {
            this.$message.success("导入完成！");
            this.importDlgVisible = false;
            this.importFileList = [];
            this.$refs.project_query_table.reload();
            this.loadBatchInfo();
          }, (response) => {
            openLoading.close();
          });
    },
    saveBatchCommon: function () {
      let batchId = this.$route.query.id;
      //校验数据类型，并且生成组合新数据
      let yearPreFix = "year";
      let batchCommonList = [];
      for (let i = 1; i < 21; i++) {
        let entity = {batchId: batchId, year: i};
        for (let j = 0; j < this.commonDataList.length; j++) {
          let dataInfo = this.commonDataList[j];
          let cellValue = dataInfo[yearPreFix + i];
          if (isNaN(cellValue)) {
            this.$message.warning("第" + (j + 1) + "行，【" + dataInfo.type + "】中，第" + i + "年数据不正确，请修改后重试！")
            return false
          }
          entity[dataInfo.code] = cellValue;
        }
        batchCommonList.push(entity);
      }
      this.batchInfo.batchCommonDTOList = batchCommonList;
      this.editCommonDlgLoading = true;
      this.$post("/batch_info/edit_common", this.batchInfo, (response) => {
        this.$message.success("保存成功！");
        this.editCommonDlgVisible = false;
        this.$refs['project_query_table'].reload();
      }, () => {
        this.editCommonDlgLoading = false;
      });
    },
    deleteProject(row) {
      this.$confirm('即将删除项目【' + row.name + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let openLoading = this.openLoading("数据删除中···");
        this.$post("/project_info/delete?id=" + row.id, {}, (response) => {
          this.$message.success('删除成功!');
          this.$refs.project_query_table.reload();
        }, () => {
          openLoading.close();
        })
      }).catch(() => {
      });
    },
    projectUltimate(row) {
      row.ultimate = true;
      this.$post("/project_info/update", row, (res) => {
        this.$message.success("保存成功");
        this.$refs.project_query_table.reload();
      })
    },
    editProject: async function (row) {
      this.editTab = "project";
      this.editProjectDlgVisible = true;
      this.editProjectDlgLoading = true;
      row.productType = this.batchInfo.productType
      this.projectInfo = row;
      this.oldBuildOffice = row.buildOffice
      let yearDataDTO = {};
      yearDataDTO.pageSize = -1;
      yearDataDTO.pageNo = 1;
      yearDataDTO.projectId = row.id;
      let responseYearData = await this.$getHttpPromise("/project_year_data/data", yearDataDTO);

      if (responseYearData.code == 0) {
        this.getProjectYearDataForShow(responseYearData.data);
      }
      let responseCostData = await this.$getHttpPromise("/project/cost/info/" + this.projectInfo.id);
      if (responseCostData.code == 0) {
        if (responseCostData.data) {
          this.projectCostData = responseCostData.data
          this.oldProjectCostData = JSON.parse(JSON.stringify(responseCostData.data))
        } else {
          this.projectCostData = {}
        }
      }
      this.editProjectDlgLoading = false;
    },
    getProjectYearDataForShow(oriDataList) {
      let yearPreFix = "year";
      console.log('oriDataList', oriDataList)
      let projectYearDataList = JSON.parse(JSON.stringify(this.projectYearDataList));
      for (let j = projectYearDataList.length-1; j>=0; j--) {
        let tableRow = projectYearDataList[j];
        if (tableRow['code'] == 'gasOutput' && this.batchInfo.productType == 'oil') {
          projectYearDataList.splice(j,1)
          continue
        } else if (tableRow['code'] == 'gasOutput1'&& this.batchInfo.productType == 'gas'){
          projectYearDataList.splice(j,1)
          continue
        }
        for (let i = 0; i < 30; i++) {
          let yearDatas = oriDataList.filter(item => {
            return item[yearPreFix] == i
          });
          if (!yearDatas || yearDatas.length == 0) {
            continue;
          }
          let multiple = 1;
          let getCode = tableRow.code
          if (tableRow['code'] == 'gasOutput1') {
            getCode = 'gasOutput'
          }
            let yearDatumElement = yearDatas[0][getCode];
          if (i == 0) {
              tableRow['sum'] = yearDatumElement
          } else {
              tableRow[yearPreFix + i] = yearDatumElement
          }

        }

      }
      this.projectYearDataList = projectYearDataList;


    },
    saveProject: function () {
      let batchId = this.$route.query.id;
      let yearPreFix = "year";
      //校验数据类型，并且生成组合新数据
      let yearDataList = [];
      for (let i = 1; i < 21; i++) {
        let entity = {batchId: batchId, year: i};
        for (let j = 0; j < this.projectYearDataList.length; j++) {
          let dataInfo = this.projectYearDataList[j];
          let cellValue = dataInfo[yearPreFix + i];
          if (isNaN(cellValue)) {
            this.$message.warning("第" + (j + 1) + "行，【" + dataInfo.type + "】中，第" + i + "年数据不正确，请修改后重试！")
            return false
          }
          entity[dataInfo.code] = cellValue;
        }
        yearDataList.push(entity);
      }
      this.projectInfo.yearDataDTOList = yearDataList;
      this.projectInfo.projectCostData = this.projectCostData;
      this.editProjectDlgLoading = true;
      this.$post("/project_info/edit_project", this.projectInfo, (response) => {
        this.$message.success("保存成功！");
        this.editProjectDlgVisible = false;
        this.$refs['project_query_table'].reload();
      }, () => {
        this.editProjectDlgLoading = false;
      });
    },
    exportData(templateId) {
      let queryData = this.$refs['project_query_table'].getQueryData();
      let idList = []
      let urlStr ='/batch_info/exportExcel?templateId=' + templateId;
      for (let key in queryData) {
      urlStr += '&'+ key+'='+queryData[key]
      }
        window.open(Vue.prototype.$ctx + urlStr );
      this.templateDlgVisible = false;
    },
    //生成报告
    createReport() {
      this.loadingText = '正在计算...';
      if (!this.batchInfo.versionId) {
        this.$message.warning("请先计算项目再生成报告")
        return
      }
      const loading = this.openLoading("正在处理,请稍后...");
      this.$get("/project/report/createReport", {
        batchId: this.batchInfo.id,
        versionId: this.batchInfo.versionId
      }, (response) => {
        this.$message.success('保存成功！');
      }, () => {
        loading.close();
      });
    },
    downloadReport() {
      if (!this.batchInfo.versionId) {
        this.$message.warning("请先计算项目，生成报告后在下载报告")
        return
      }
      window.open(this.$ctx + '/project/report/download?versionId=' + this.batchInfo.versionId);
    },
    commonExport() {
      if ((!this.multipleSystemSelection || this.multipleSystemSelection.length <= 0) &&
          (!this.multipleCustomSelection || this.multipleCustomSelection.length <= 0)) {
        this.$message.warning('未选中任何行');
        return;
      }
      if ((this.multipleSystemSelection && this.multipleSystemSelection.length > 0) &&
          (this.multipleCustomSelection && this.multipleCustomSelection.length > 0)) {
        this.$message.warning('只允许选择一个模板');
        return;
      }
      if ((this.multipleSystemSelection && this.multipleSystemSelection.length > 1) ||
          (this.multipleSystemSelection && this.multipleCustomSelection.length > 1)) {
        this.$message.warning('只允许选择一个模板');
        return;
      }
      let template = null;
      if (this.multipleSystemSelection) {
        template = this.multipleSystemSelection[0]
      } else {
        template = this.multipleCustomSelection[0]
      }
      if (template.exportTemplateType == 'batch_export') {
        this.downloadBatchProjectData(template.id)
      } else if (template.exportTemplateType == 'merge_export') {
        this.downloadMergeProjectData(template.id)
      } else {
        this.exportData(template.id)
      }
    },
    downloadBatchProjectData(templateId) {
      // let url = Vue.prototype.$ctx+'/batch_info/exportMergeExcel';

      let url = Vue.prototype.$ctx + '/batch_info/batchExportExcel/' + this.batchInfo.id + '/' + templateId;
      //let queryData = this.$refs['project_query_table'].getQueryData()
      window.open(url);
      this.templateDlgVisible = false;
    },
    downloadMergeProjectData(templateId) {
      // let url = Vue.prototype.$ctx+'/batch_info/exportMergeExcel';

      let url = Vue.prototype.$ctx + '/batch_info/downloadMergeExcel/' + this.batchInfo.id + '/' + templateId;
      //let queryData = this.$refs['project_query_table'].getQueryData()
      window.open(url);
      this.templateDlgVisible = false;
    },
    buildUrl(path, query) {
      if (!(query)) {
        console.error('请传入正确的query')
        return
      }
      let str = ''
      Object.keys(query).forEach(key => {
        str += `&${key}=${encodeURIComponent(query[key])}`
      })
      return `${path}?${str.slice(1)}`
    },

    saveAdjustRate(type) {
      this.adjustRateDlgLoading = true;
      let map = {}
      for (let item of this.adjustRatioDataMap['cost_ratio']) {

        if (!map[item['projectId']]) {
          map[item['projectId']] = []
        }
        for (let itemkey in item) {
          if (itemkey.indexOf('year') >= 0 && itemkey != 'year')
            map[item['projectId']].push(itemkey)
        }


      }
      let dataList = []
      for (let key in map) {

        let yearList = map[key];
        for (let yearCol of yearList) {
          let data = {}
          data['projectId'] = key;
          for (let item of this.adjustRatioDataMap['cost_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            let year = yearCol.replace('year', '')
            data['year'] = parseInt(year);
            data['costRatio'] = parseFloat(item[yearCol])
          }
          for (let item of this.adjustRatioDataMap['output_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            data['outputRatio'] = parseFloat(item[yearCol])
          }
          for (let item of this.adjustRatioDataMap['invest_ratio']) {
            if (item['projectId'] != key) {
              continue
            }
            data['investRatio'] = parseFloat(item[yearCol])
          }
          dataList.push(data)
        }
      }

      this.$post('/project_year_data/saveRatio', dataList, (res) => {


        if (type == 'compute') {
          this.batchCompute();
        } else {
          this.$message.success("保存成功")
        }


      }, () => {
        this.adjustRateDlgLoading = false;
        this.adjustRateDlgVisible = false;
      });
    },
    initAdjustRate() {
      this.adjustRateDlgVisible = true;
      this.adjustRateDlgLoading = true;
      let projectList = this.$refs['project_query_table'].getDataList();
      let projectIds = [];
      if (projectList) {
        for (let item of projectList) {
          projectIds.push(item.id)
        }
      }

      this.$post("/project_year_data/queryRatio", projectIds, (response) => {
        this.adjustRatioDataMap = response.data;
        //  this.adjustRateDlgLoading = false;
      }, () => {
        this.adjustRateDlgLoading = false;
      });

    },
    //批量计算
    batchCompute() {
      const loading = this.openLoading('正在处理，请稍后...');
      let projectList = this.$refs['project_query_table'].getDataList();
      let projectIdList = [];
      for (let item of projectList) {
        projectIdList.push(item.id)
      }
      this.$post('/compute_version/batch/invoke', {
        batchId: this.batchInfo.id,
        filterProjectSet: projectIdList
      }, (response) => {
        this.$message.success("计算完成")
        this.loadBatchInfo()
        this.$refs.project_query_table.reload();
      }, (response) => {
        loading.close();
      })
    }
  },

}
</script>
<style>
/* 所属客户的input的按钮的颜色 */
/* 设置客户管理模块的高度和固定位置 */
/*.pub_dialog {*/
/*  display: flex;*/
/*  justify-content: center;*/
/*  align-items: Center;*/
/*  overflow: hidden;*/

/*.el-dialog {*/
/*  margin: 0 auto !important;*/
/*  height: 90%;*/
/*  overflow: hidden;*/

/*.el-dialog__body {*/
/*  position: absolute;*/
/*  left: 0;*/
/*  top: 54px;*/
/*  bottom: 0;*/
/*  right: 0;*/
/*  padding: 10px 0 10px 0;*/
/*  z-index: 1;*/
/*  overflow: hidden;*/
/*  overflow-y: auto;*/
/*}*/

/*}*/
/*}*/
</style>

